package com.googlecode.javamvsandbox.concurrent.increment;

import java.util.concurrent.atomic.AtomicInteger;

public class TestConcurrentIncrement {

    //public volatile int increment = 0;
	public AtomicInteger increment = new AtomicInteger(0);
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		long ct = System.currentTimeMillis();
		final TestConcurrentIncrement tci = new TestConcurrentIncrement();
		Runnable r = new Runnable(){
			public void run() {
				for (int i = 0; i<10000; i++) {
					tci.doUnsafeIncrement();
					Thread.yield();
					//System.out.println(Thread.currentThread().getName());
				}
			}
			
		};
		Thread[] ts = new Thread[100];
		for (int i=0 ; i<100 ; i++) {
			Thread t = new Thread(r);
			t.start();
			ts[i] = t;
		}
		for (int i=0 ; i<100 ; i++) {
			ts[i].join();
		}
		tci.assertIncrement();
		System.out.println("Time of execution: "+ (System.currentTimeMillis() - ct));
	}
	
	public /*synchronized */void doUnsafeIncrement() {
		increment.getAndIncrement();
	}

	public void assertIncrement() {
		System.out.println(increment);
	}
}